<template>
  <div class="layout h-full overflow-hidden w-full min-w-[1560px]">
    <el-container class="h-full w-full overflow-hidden">
      <el-header>
        <layout-header />
        <layout-menu />
      </el-header>
      <el-main>
        <div class="menu-aside" v-if="showMenuAside">
          <layout-aside />
        </div>
        <div
          class="view-main"
          :class="{
            'hide-menu-aside': !showMenuAside
          }"
        >
          <router-view></router-view>
        </div>
      </el-main>
    </el-container>
    <layout-examine />
    <global-sound :name="SoundName.msgSound" ref="msgSoundRef" />
  </div>
</template>
<script setup lang="ts">
import LayoutHeader from "@/layout/header.vue";
import LayoutMenu from "@/layout/menu.vue";
import LayoutAside from "@/layout/aside.vue";
import LayoutExamine from "@/layout/examine.vue";

import $bus from "@/utils/bus";
import avatarImg from "@/assets/images/img-avatar-default.jpg";
import singleBetImg from "@/assets/images/single-bet.png";
import singleWinImg from "@/assets/images/single-win.png";
import { SocketMsgType, SoundName } from "@/enums";
import { useUserStore } from "@/store/modules/user";
import { useGameStore } from "@/store/modules/game";
import { useRoomStore } from "@/store/modules/room";
import { useSocketStore } from "@/store/modules/socket";
import { cloneDeep } from "lodash-es";
import { storeToRefs } from "pinia";
import { useKefuStore } from "@/store/modules/kefu";
import { netPath } from "@/utils/common";
import { ElNotification } from "element-plus";
import { useServiceStore } from "@/store/modules/service";
import { usePremsStore } from "@/store/modules/prems";

const router = useRouter();
const userStore = useUserStore();
const premsStore = usePremsStore();
const gameStore = useGameStore();
const roomStore = useRoomStore();
const socketStore = useSocketStore();
const kefuStore = useKefuStore();
const serviceStore = useServiceStore();
const { userInfo } = storeToRefs(userStore);
const { gameTotal } = storeToRefs(gameStore);
const { tabActive, serviceActive, serviceList } = storeToRefs(serviceStore);
const route = useRoute();
const msgSoundRef = ref();

const showMenuAside = computed(() => {
  if (
    route.path === "/admin/main" ||
    route.path === "/admin/openresult" ||
    route.path === "/admin/monitor" ||
    route.path === "/admin/odds" ||
    route.path === "/admin/flyalone"
  ) {
    return false;
  }
  return true;
});

// 上下分提示
const upDownJoinNotice = (data: SocketMsg) => {
  let title = "";
  if (data.msg_type == SocketMsgType.down_socore || data.msg_type == SocketMsgType.up_score) {
    title = "上下分申请通知";
  }
  if (data.msg_type == SocketMsgType.joinroom) {
    title = "加入房间通知";
  }
  // 监听上下分
  let notification = `
  		<div class="flex justify-between w-[280px]">
  			<div class="w-[40px] h-[40px] bg-[#fff] rounded-[40px] overflow-hidden">
  				<img class="w-[40px] h-[40px] block" src="${netPath(data.avatar) || avatarImg}"/>
  			</div>
  			<div class="flex-[1] w-0 ml-[10px]">
  				<div class="leading-none text-[#000]">用户：${data.nick_name}</div>
  				<div class="mt-[8px] text-[#000]">
  					<span>${data.content}</span>
  				</div>
  			</div>
  		</div>
  	`;
  const no = ElNotification({
    title: title,
    dangerouslyUseHTMLString: true,
    message: notification,
    duration: 0,
    position: "bottom-right",
    customClass: "apply-notice",
    onClick: () => {
      // 上下分通知
      if (data.msg_type == SocketMsgType.down_socore || data.msg_type == SocketMsgType.up_score) {
        if (route.path == "/admin/apply/updown") {
          $bus.emit("update-updown-msg");
        } else {
          router.push("/admin/apply/updown");
        }
      }
      // 进房审核
      if (data.msg_type == SocketMsgType.joinroom) {
        if (route.path == "/admin/apply/join-room") {
          $bus.emit("update-join-room-msg");
        } else {
          router.push("/admin/apply/join-room");
        }
      }
      no.close();
    }
  });
  msgSoundRef.value?.play();
};

// 客服提示
const kefuNotice = (data: KefuMsg) => {
  if (!premsStore.isEditChatSetting) return;
  if (data.user_id === `r_${userInfo.value?.RoomId}`) {
    return;
  }
  const service = serviceList.value.find(item => Number(item.UserId) == Number(data.user_id));
  const serviceIndex = serviceList.value.findIndex(
    item => Number(item.UserId) == Number(data.user_id)
  );
  if (!service) {
    serviceStore.actionServiceList(data.user_id);
  } else {
    serviceStore.updateServiceItem({
      ...service,
      LastMsg: data.content,
      LastMsgTime: data.time
    });
  }

  const showNotice = () => {
    // 监听客服
    let notification = `
  		<div class="flex justify-between w-[280px]">
  			<div class="w-[40px] h-[40px] bg-[#fff] rounded-[40px] overflow-hidden">
  				<img class="w-[40px] h-[40px] block" src="${netPath(data.avatar) || avatarImg}"/>
  			</div>
  			<div class="flex-[1] w-0 ml-[10px]">
  				<div class="leading-none text-[#000]">用户：${data.nick_name}</div>
  				<div class="mt-[8px] text-[#000]">
  					<span>${data.msg_type == SocketMsgType.img_msg ? "【图片消息】" : data.content}</span>
  				</div>
  			</div>
  		</div>
  	`;
    const no = ElNotification({
      dangerouslyUseHTMLString: true,
      message: notification,
      duration: 0,
      position: "bottom-right",
      customClass: "apply-notice",
      onClick: () => {
        if (route.path == "/admin/main") {
          // 客服
          if (!tabActive.value) {
            $bus.emit("switch-kefu-tab", data.user_id);
          } else {
            $bus.emit("switch-kefu-item", data.user_id);
          }
        } else {
          router.push(`/admin/main?kefu=${data.user_id}`);
        }
        no.close();
      }
    });
  };

  if (tabActive.value) {
    if (serviceIndex !== serviceActive.value) {
      msgSoundRef.value?.play();
      showNotice();
    }
  } else {
    msgSoundRef.value?.play();
    showNotice();
  }
};

// 其他提示
const otherNotice = (data: KefuMsg) => {
  let imgUrl = singleBetImg;
  if (data?.msg_type == SocketMsgType.single_bet || data?.msg_type == SocketMsgType.follow_up) {
    imgUrl = singleBetImg;
  } else {
    imgUrl = singleWinImg;
  }
  // 监听大额
  let notification = `
  		<div class="flex items-center justify-between ${data?.msg_type == SocketMsgType.follow_up ? "min-w-[300px]" : "min-w-[400px]"}" >
  			<div class="w-[50px] h-[50px] bg-[#fff] rounded-[50px] overflow-hidden">
  				<img class="w-[50px] h-[50px] block" src="${imgUrl}"/>
  			</div>
  			<div class="flex-[1] w-0 ml-[10px]">
  				${data.content}
  			</div>
  		</div>
  	`;
  const no = ElNotification({
    dangerouslyUseHTMLString: true,
    message: notification,
    duration: 0,
    position: "bottom-right",
    customClass: "other-notice",
    onClick: () => {
      // 用户登录
      if (data.msg_type == SocketMsgType.follow_up) {
        if (route.path == "/admin/user/member") {
          $bus.emit("update-member-msg");
        } else {
          router.push("/admin/user/member");
        }
      } else {
        if (route.path == "/admin/report/notice") {
          $bus.emit("update-report-notice-msg");
        } else {
          router.push("/admin/report/notice");
        }
      }
      no.close();
    }
  });
  msgSoundRef.value?.play();
};

// 监听socket连接状态
const watckSocket = () => {
  socketStore.client?.subscribe("chatmessage", data => {
    // console.log("---房间消息---", data);
    if (data?.msg_type == SocketMsgType.open) {
      const msgData = data.data as SocketOpenMsg;
      const games = cloneDeep(gameTotal.value);
      const cur = games.find(item => item.LotteryId == msgData.Id);
      const newLotteryData = {
        ...cur,
        BetAmount: cur?.BetAmount,
        CloseTime: msgData.CloseTime,
        Issue: msgData.CurrentBitchNo,
        NextTime: msgData.NextTime
      };
      gameStore.setLotteryGame(newLotteryData as GameTotalMo);
      $bus.emit("open-result", newLotteryData as GameTotalMo);
      $bus.emit("update-total-result", newLotteryData as GameTotalMo);
    } else if (
      data?.msg_type == SocketMsgType.room_text_msg ||
      data?.msg_type == SocketMsgType.img_msg ||
      data?.msg_type == SocketMsgType.room_guessing_msg
    ) {
      $bus.emit("room-msg", data as GameHistoryMo);
    }
  });
  kefuStore.client?.subscribe("chatmessage", data => {
    // console.log("---私聊消息---", data);
    if (data?.msg_type == SocketMsgType.kefu_text_msg || data?.msg_type == SocketMsgType.img_msg) {
      $bus.emit("kefu-msg", data as KefuMsg);
      if (data.user_id !== `r_${userInfo.value?.RoomId}`) {
        kefuNotice(data as KefuMsg);
      }
    } else if (
      data?.msg_type == SocketMsgType.up_score ||
      data?.msg_type == SocketMsgType.down_socore ||
      data?.msg_type == SocketMsgType.joinroom
    ) {
      upDownJoinNotice(data as SocketMsg);
    } else if (data?.msg_type == SocketMsgType.game_bet) {
      $bus.emit("game-bet", data.data as GameBetMo);
    } else if (
      data?.msg_type == SocketMsgType.single_bet ||
      data?.msg_type == SocketMsgType.single_win ||
      data?.msg_type == SocketMsgType.follow_up
    ) {
      otherNotice(data as KefuMsg);
    } else if (data?.msg_type == SocketMsgType.updata_history_list) {
      $bus.emit("updata-history-list");
    }
  });
};

onBeforeMount(async () => {
  if (userStore.getToken) {
    gameStore.actionGameLeft();
    roomStore.actionRoomInfo();
    !socketStore.client && (await socketStore.initSocket());
    !kefuStore.client && (await kefuStore.initSocket());
    watckSocket();
  }
});
</script>
<style>
.menu-aside {
  @apply w-[140px] overflow-hidden bg-[#fff] rounded-[5px];
  box-shadow: 0px 0px 10px 4px rgba(0, 0, 0, 0.08);
}
.view-main {
  @apply flex-1 w-0 bg-[#fff] overflow-hidden rounded-[5px] ml-[10px];
  box-shadow: 0px 0px 10px 4px rgba(0, 0, 0, 0.08);
}
.hide-menu-aside {
  @apply bg-transparent ml-0;
}
.other-notice {
  --el-notification-width: auto !important;
}
</style>
<style lang="scss" scoped>
:deep(.el-header) {
  padding: 0;
  height: fit-content;
}
:deep(.el-main) {
  padding: 10px;
  border-radius: 10px 10px 0 0;
  display: flex;
  justify-content: space-between;
}
</style>
